import axios, { RawAxiosRequestHeaders, ResponseType } from "axios";
const path = import.meta.env.BASE_SRC
import { message } from 'antd';
import store from "@/store";

const instance = axios.create({
  // baseURL,
  baseURL: path,
  // timeout: 300000, //5S超时
  timeout: 600000, //5S超时
});
//请求拦截
instance.interceptors.request.use(
  (config: any) => {
    // const store = useUserInfoStore()
    const { user } = store.getState()
      if(user.token) {
        config.headers.Authorization = user.token
      }
    return config;
  },
  (err: any) => {
    //拦截失败
    return Promise.reject(err);
  }
);
//响应拦截
instance.interceptors.response.use(
  (res: any) => {
    if (res.request.responseType === 'blob') {
      return res.data
    }
    return res.data.data

  },
  (err: any) => {
    const msg = err.response.data.msg
    message.error(msg)
    return Promise.reject(err);
  }
);


// 参数类型改为泛型
export default {
  get: <T>(url: string, data = {}, responseType: any = "json"): Promise<T> => {
    return instance({
      url,
      method: "get",
      params: data,
      responseType: responseType,
    }) as Promise<T>;
  },
  post: <T>(url: string, data = {}, headers?: RawAxiosRequestHeaders, responseType?: ResponseType): Promise<T> => {
    return instance({ url, method: "post", data: data, headers, responseType }) as Promise<T>;
  },
  put: <T>(url: string, data = {}): Promise<T> => {
    return instance({ url, method: "put", data: data }) as Promise<T>;
  },
  delete: <T>(url: string, data = {}): Promise<T> => {
    return instance({ url, method: "delete", data: data }) as Promise<T>;
  },
  postFile: <T>(url: string, data = {}, config:any): Promise<T> => {
    return instance({ url, method: "post", data: data, ...config }) as Promise<T>;
  }
};